package com.hh.controller;

import com.google.code.kaptcha.Producer;
import com.hh.common.Const;
import com.hh.domain.ResponseResult;
import com.hh.enums.AppHttpCodeEnum;
import com.hh.utils.RedisCache;
import com.hh.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/*
 * @Author huxy
 * @since 2022年10月16日
 * */
@Slf4j
@RestController
public class KaptcherController {
    @Autowired
    RedisCache redisCache;
    @Autowired
    Producer kaptcherProducer;//Producer是kaptcha的核心接口，通过它去创建图片以及随机的字符串
    /*
     * 获取验证码
     * @commen 生成4位数数字字母混合验证码存入redis
     * @return 验证码
     * */
    @RequestMapping( "/kaptcha")
    public ResponseResult getKaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        //生成验证码
        String code = kaptcherProducer.createText();
        BufferedImage image = kaptcherProducer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BASE64Encoder encoder = new BASE64Encoder();
        ImageIO.write(image, "jpg", outputStream);
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        Map map = new HashMap();
        map.put("captchaImg", base64Img);
        map.put("code",code);
        // 存储到redis中
        redisCache.setCacheObject(Const.CAPTCHA_KEY,code,120, TimeUnit.SECONDS);
        log.info("验证码 -- {} - {}", code);
        return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getMsg(),map);
    }

}